/*
 * @Descripttion: 
 * @version: 
 * @Author: HuangJunren
 * @Date: 2020-07-31 20:41:36
 * @LastEditors: HuangJunren
 * @LastEditTime: 2020-07-31 23:08:07
 */ 

// g++ -g -Wall utils/main.cpp -I/usr/local/include -L/usr/local/lib/ -lavcodec -lavformat --std=c++11 -o main.out
extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
}

#include "RtmpWriter.h"

AVFormatContext *pFormatCtx;
AVCodecContext *pCodecCtx_video;
AVCodec *pCodec_video;
AVFrame *pFrameYUV;

int main(int argc, char const *argv[])
{
    pFormatCtx = NULL;
	pCodecCtx_video = NULL;
	pCodec_video = NULL;
    int ret = -1;

	av_register_all(); //注册组件
	avformat_network_init(); //支持网络流
	pFormatCtx = avformat_alloc_context(); //初始化AVFormatContext
	pFrameYUV = av_frame_alloc(); 
	if (pFrameYUV == NULL)
	{
		ret = -1;
		return ret;
	}

	//获得RTSP地址
	//const char *url = (*env)->GetStringUTFChars(env, javaString, 0);
	//printf("接收java中的地址是：%s", url);

	ret = avformat_open_input(&pFormatCtx, "/root/share/h265_high.mp4", NULL, NULL);
	if (ret != 0) { //打开文件
		printf("无法打开文件,函数返回值\n");
		ret = -1;
		return ret;
	} else {
		printf("打开了视频源\n");
	}

	if (avformat_find_stream_info(pFormatCtx, NULL) < 0) //查找流信息
	{
		printf("找不到流信息\n");
		ret = -1;
		return ret;
	} else {
		printf("找到流信息\n");
	}

	int videoindex = -1;
	printf("pFormatCtx->nb_streams的值是:%d\n", pFormatCtx->nb_streams);
	for (int i = 0; i <= pFormatCtx->nb_streams; i++)
	{
		if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
			videoindex = i;
			break;
		}
	}

	if (videoindex == -1) {
		printf("没有找到视频流\n");
		ret = -1;
		return ret;
	} else {
		printf("找到视频流，%d\n", videoindex);
	}

    RtmpWriter *pRtmpWriter = new RtmpWriter();
    pRtmpWriter->initUrl("rtmp://172.17.0.2/video/1100");

    int got_frame = 0;
    AVPacket *packet = av_packet_alloc();
    for (;;) {
        int ret = av_read_frame(pFormatCtx, packet);
        if (ret != 0) {
            printf("读取到结尾处");
            break;
        }

        printf("streamIndex=%d, size=%d, pts=%lld, flag=%d",
             packet->stream_index,
             packet->size,
             packet->pts,
             packet->flags
        );

        ret = avcodec_decode_video2(pFormatCtx->streams[videoindex]->codec, pFrameYUV, &got_frame, packet);
        if (ret < 0) {
            LOGE("Error while decoding frame\n");
            ret = -1;
            goto ErrLab;
        }

        if (got_frame > 0){
            pRtmpWriter->publishVideoframe((char *)packet->data, packet->size, packet->flags, packet->pts);
        }
        av_packet_unref(packet);
    }
    
    return 0;
}
